javascript


What is a Function? A function is a reusable block of code designed to perform a particular task. Instead of repeating code, you write it once and reuse it wherever needed.

Think of it like a machine: Input (parameters) → ⚙️ Function logic → 🎯 Output (return value) Why Use Functions? * Avoid repetition (DRY principle – Don’t Repeat Yourself) * Improve readability * Simplify debugging and testing * Organize code logically

 Function Syntax


function functionName(parameters) {
  // Code to execute
}


Example:


function greet(name) {
  console.log("Hello, " + name + "!");
}

greet("Alice"); // Output: Hello, Alice!
greet("Bob");   // Output: Hello, Bob! 

How to Return Values

Functions can return values using the `return` keyword: return should be always end of the function.


function add(a, b) {
  res = a +b;
  return res;
}

const result = add(5, 3);  // result = 8
console.log(result);
 

Arrow Functions (ES6)

Arrow Functions (ES6) Shorter syntax introduced in ES6:



const subtract = (a, b) => a - b;

console.log(subtract(10, 3)); // Output: 7
 
Traditional way of declaring:
function app(){

}

Arrow function:
app=()=>{

}